package com.ruoyi.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.pojo.School;
import com.ruoyi.pojo.SchoolName;
import com.ruoyi.service.SchoolNameService;
import com.ruoyi.service.SchoolService;
import com.ruoyi.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/school")
public class SchoolNameController {

    @Autowired
    private SchoolNameService schoolNameService;
    @Autowired
    private SchoolService schoolService;

    @PostMapping("/name")
    public R<String> schoolUpdate(@RequestBody SchoolName schoolName){
        Integer userId = Integer.parseInt(String.valueOf(SecurityUtils.getUserId()));
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("userid",userId);
        SchoolName one = schoolNameService.getOne(wrapper);
        if (one == null) {
            schoolName.setUserid(userId);
            int i = schoolNameService.addSchoolname(schoolName);
            if (i > 0) {
                return R.success("添加成功");
            }else{
                return R.error("添加失败");
            }
        }else{
            return R.error("已添加过，添加失败");
        }
    }

    @GetMapping("/selectschool")
    public R<SchoolName> selectSchool(@RequestParam(required = false) Integer id){
        System.out.println(id);
        if (id == null||id.equals("")) {
            id = Integer.parseInt(String.valueOf(SecurityUtils.getUserId()));
        }
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("userid",id);
        SchoolName one = schoolNameService.getOne(wrapper);
        return R.success(one);
    }

    @GetMapping("/schoollist")
    public R<List<School>> schoolList(School school){
        QueryWrapper wrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(school.getSchoolname())) {
            wrapper.eq("schoolname",school.getSchoolname());
        }
        List<School> list = schoolService.list(wrapper);
        return R.success(list);
    }

    @PostMapping("/updateschool")
    public R<String> updateSchool(@RequestBody SchoolName schoolName){
        boolean b = schoolNameService.updateById(schoolName);
        if (b){
            return R.success("修改成功");
        }else{
            return R.error("修改失败");
        }
    }
}
